package com.lpf.transaction;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * 功能描述：操作事务工具类
 */
@Slf4j
@Component
public class TransactionUtils {

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    // 开启事物
    public TransactionStatus begin() {
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(new DefaultTransactionDefinition());
        log.error("开启事物");
        return transaction;
    }

    // 提交事物
    public void commit(TransactionStatus transaction) {
        dataSourceTransactionManager.commit(transaction);
        log.error("提交事物");
    }

    // 回滚事物
    public void rollback(TransactionStatus transaction) {
        dataSourceTransactionManager.rollback(transaction);
        log.error("回滚事物");
    }
}
